package com.zc.config;

import com.zc.pojo.SysAccount;
import com.zc.service.SysAccountService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的UserRealm
public class SysAccountRealm extends AuthorizingRealm {

    @Autowired
    SysAccountService sysAccountService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了 -》 授权 doGetAuthorizationInfo");
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了 -》 认证 doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        System.out.println("userToken -> username" + userToken.getUsername());
        System.out.println("userToken -> password" + userToken.getPassword());
        //获取数据库中真实用户
        SysAccount sysAccount = sysAccountService.getByUsername(userToken.getUsername());
        System.out.println("sysAccount ->" + sysAccount);
        if (sysAccount == null) {
            return null;
        }
        //把用户存入session
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute("user", sysAccount);
        //密码认证，shiro来做 不让你来做
        return new SimpleAuthenticationInfo(sysAccount.getUsername(), sysAccount.getPassword(), ByteSource.Util.bytes(sysAccount.getSalt()), this.getName());
    }
}
